package com.jiuyuan.service.impl;

import com.jiuyuan.entity.Admin;
import com.jiuyuan.entity.Menu;
import com.jiuyuan.mapper.MenuMapper;
import com.jiuyuan.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiuyuan
 * @since 2023-02-15
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<Menu> getMenusByAdminId() {
        Admin admin =  (Admin)(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        List<Menu> menus = ((List<Menu>) opsForValue.get("menu_" + admin.getId()));
        if(CollectionUtils.isEmpty(menus)){
            //双菜单联查，一个菜单放入子菜单中
            //对应的菜单id是具体的子菜单，所以在连表中，要到达的菜单为子菜单
            menus = menuMapper.getMenusByAdminId(admin.getId());
            opsForValue.set("menu_"+admin.getId(),menus);
        }
        return menus;
    }

    @Override
    public List<Menu> getMenusWithRoles() {
        return menuMapper.getMenusWithRoles();
    }

    @Override
    public List<Menu> listAll() {
        return menuMapper.listAll();
    }
}
